package handler

import (
	"ehsm_kms/api"
	"ehsm_kms/internal/constants"
	"ehsm_kms/internal/ehsm"
	"encoding/base64"
	"github.com/gin-gonic/gin"
)

func (h *Handler) getVersion(ctx *gin.Context) {
	resp := new(ehsm.GetVersionResp)
	err := ehsm.GetVersionAction.Call(nil, resp)
	if err != nil {
		api.HandleError(ctx, 500, err, nil)
		return
	}
	api.HandleSuccess(ctx, resp)
	return
}

func (h *Handler) enroll(ctx *gin.Context) {
	var err error
	defer func() {
		if err != nil {
			api.HandleError(ctx, 500, err, nil)
			ctx.Abort()
		}
	}()
	resp := new(ehsm.EnrollResp)
	err = ehsm.EnrollAction.Call(nil, resp)
	if err != nil {
		return
	}

	cmkResp := new(ehsm.CreateKeyResp)
	err = ehsm.CreateKeyAction.Call(ehsm.CreateKeyPayload{
		KeySpec:  constants.EH_AES_GCM_256,
		Origin:   constants.EH_INTERNAL_KEY,
		KeyUsage: constants.EH_KEYUSAGE_ENCRYPT_DECRYPT,
	}, cmkResp)
	if err != nil {
		return
	}

	smDefCmkResp := new(ehsm.CreateKeyResp)
	err = ehsm.CreateKeyAction.Call(ehsm.CreateKeyPayload{
		KeySpec:  constants.EH_AES_GCM_256,
		Origin:   constants.EH_INTERNAL_KEY,
		KeyUsage: constants.EH_KEYUSAGE_ENCRYPT_DECRYPT,
	}, smDefCmkResp)
	if err != nil {
		return
	}

	encryptResp := new(ehsm.EncryptResp)
	err = ehsm.EncryptAction.Call(ehsm.EncryptPayload{
		Cmk:       cmkResp.Result.Cmk,
		PlainText: base64.StdEncoding.EncodeToString([]byte(resp.Result.Apikey)),
		Aad:       "",
	}, encryptResp)
	if err != nil {
		return
	}

	//落库保存
	err = h.userRep.Store(ctx, resp.Result.Appid, []byte(encryptResp.Result.CipherText), cmkResp.Result.Cmk, smDefCmkResp.Result.Cmk)
	if err != nil {
		return
	}

	return

}
